package com.zc.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zc.common.core.domain.model.LoginUser;
import com.zc.common.utils.SecurityUtils;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * ClassName:MyMetaObjectHandler
 * Description:
 * DateTime: 2025/9/22 10:28
 * Author: zc
 * Version: 1.0
 */

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isExclude() {
        String requestURI = request.getRequestURI();
        if(requestURI.startsWith("/api/v1")){
            return false;
        }
        return true;
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        if(isExclude()){
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            this.strictInsertFill(metaObject, "createBy", String.class, loadUserId()+"");
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(isExclude()){
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            this.strictUpdateFill(metaObject, "updateBy", String.class, loadUserId()+"");
        }

    }

    /**
     * 获取当前登录人的ID
     * @return
     */
    public static Long loadUserId(){
        //获取当前登录人的id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(ObjectUtils.isNotEmpty(loginUser)){

            return loginUser.getUserId();
        }
        return 1L;
    }
}
